package cn.acewill.yxd.yunxundian.ui.user.Presenter;


import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.os.IBinder;
import android.support.annotation.NonNull;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AppCompatActivity;

import android.os.Bundle;

import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;

import org.xutils.DbManager;
import org.xutils.ex.DbException;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

import cn.acewill.yxd.yunxundian.BaseActivity;
import cn.acewill.yxd.yunxundian.R;
import cn.acewill.yxd.yunxundian.YXDAPP;
import cn.acewill.yxd.yunxundian.componet.NetWorkStateReceiver;
import cn.acewill.yxd.yunxundian.model.Employee;
import cn.acewill.yxd.yunxundian.model.Schedule;
import cn.acewill.yxd.yunxundian.model.Shop;
import cn.acewill.yxd.yunxundian.pubClass.pubClass;
import cn.acewill.yxd.yunxundian.ui.LoginActivity;
import cn.acewill.yxd.yunxundian.ui.SynchronizationAtivity;
import cn.acewill.yxd.yunxundian.ui.user.Contract.LoginView;
import cn.acewill.yxd.yunxundian.utils.MaterialDialogUtils;
import cn.acewill.yxd.yunxundian.utils.NotificationsUtils;
import cn.acewill.yxd.yunxundian.utils.baiduUtils.InputUtil;


/**
 * 项目使用MVP框架修改起来会特别麻烦,逻辑需要跳转的地方太多，接口n个，暂时写个例子，仅供参考。。
 * by:xxx
 */
public class LoginActivityForTest extends BaseActivity implements LoginView,View.OnClickListener,TextWatcher{

    protected YXDAPP yxdapp=new YXDAPP();
    protected DbManager db = x.getDb(yxdapp.getDaoConfig());
    private EditText userNum,userPass;
    private Button loginIn;
    private String uNum,uPass;
    private SharedPreferences sp;
    NetWorkStateReceiver netWorkStateReceiver;
    private TextInputLayout userNameWrapper,passWrapper;
    private Animation shake;
    private TextView configIP;
    private String IPName,branchName;
    private ProgressDialog dialog;
    private LoginPresenterIml presenter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        initView();
        pubClass.seturl(this);
        shake = AnimationUtils.loadAnimation(this,R.anim.edtext_shake);
    }
    public void initView() {
        this.passWrapper= (TextInputLayout) findViewById(R.id.passWrapper);
        this.userNameWrapper  = (TextInputLayout) findViewById(R.id.userNameWrapper);
        this.userNum = (EditText) findViewById(R.id.userNum);
        this.userPass = (EditText) findViewById(R.id.userPass);
        this.loginIn = (Button) findViewById(R.id.loginIn);
        this.loginIn.setOnClickListener(this);
        userNum.addTextChangedListener(this);
        this.configIP= (TextView) findViewById(R.id.configIP);
        configIP.setOnClickListener(this);
        sp=getSharedPreferences("yxdUrl",MODE_PRIVATE);
        userNum.setText(sp.getString("userNum",""));
        userPass.setText(sp.getString("userPass",""));
        IPName = sp.getString("IpName","");
        InputUtil.getInstance(this).setEditTextInhibitInputSpeChat(userNum);
        InputUtil.getInstance(this).setEditTextInhibitInputSpeChat(userPass);
        dialog = new ProgressDialog(this);
        presenter = new LoginPresenterIml(this);

        //获取通知权限
        boolean isNeedRequest = NotificationsUtils.isNotificationEnabled(this);
        if (!isNeedRequest)
            Toast.makeText(this,"您禁止了通知权限，可在应用通知设置中打开",Toast.LENGTH_SHORT).show();
        }
    /**
     * 广播的注册，与静态注册一起使用
     */
    @Override
    protected void onResume() {
        if (netWorkStateReceiver==null){
            netWorkStateReceiver=new NetWorkStateReceiver();
        }
        IntentFilter filter=new IntentFilter();
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(netWorkStateReceiver,filter);
        System.out.print("广播注册");
        super.onResume();
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(netWorkStateReceiver);
        System.out.print("广播注销");
        //输入法内存回收
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        try {
            InputMethodManager.class.getDeclaredMethod("windowDismissed", IBinder.class).invoke(imm,
                    getWindow().getDecorView().getWindowToken());
        } catch (Exception e){
            e.printStackTrace();
        }
    }
    //此处暂且这样弄
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.loginIn:
                dialog.setMessage("正在登陆");
                uNum = userNum.getText().toString();
                uPass = userPass.getText().toString();
                if (TextUtils.isEmpty(IPName)){
                    this.shakeIPCheck();
                    return;
                }
                if (TextUtils.isEmpty(uNum)){
                    this.shakeUserName();
                    return;
                }
                if (TextUtils.isEmpty(uPass)) {
                    this.shakeUserPass();
                    return;
                }
                //判断pubclass的url是否为空，空就设置
                if (TextUtils.isEmpty(pubClass.Server_namehzm)){
                    pubClass.seturl(this);
                }
                //是否切换账号
                String name = sp.getString("userNum","");
                if (!TextUtils.isEmpty(name)){//是否有记录
                    if (!name.equals(uNum)){ //不同登录名
                        try {
                            final List<Employee> emp = db.selector(Employee.class).findAll();
                            //有数据则提示
                            if (emp!=null&&emp.size()>0) {
                                if (NetWorkStateReceiver.whetherConnectNetWork == 1) {
                                    MaterialDialogUtils.showMaterialDialog(this, "切换用户将清空所有未提交的评估信息，是否继续登录", "确定", "取消", true, true, new MaterialDialog.SingleButtonCallback() {
                                        @Override
                                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                            try {
                                                db.dropDb();
                                                presenter.vaildValue(uNum,uPass,IPName);
                                            } catch (DbException e) {
                                                e.printStackTrace();
                                            }

                                        }
                                    }, new MaterialDialog.SingleButtonCallback() {
                                        @Override
                                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                        }
                                    });
                                } else {
                                    //当前处于离线状态，只能以之前账号登录
                                    BaseActivity.showAnimaDialog(this, "当前处于离线状态，只能以之前账号登录");
                                }
                            }else{ //直接登录
                                presenter.vaildValue(uNum,uPass,IPName);
                            }
                        } catch (DbException e) {
                            e.printStackTrace();
                        }
                    }else{//相同用户
                        presenter.vaildValue(uNum,uPass,IPName);
                    }
                }else{ //无记录
                    presenter.vaildValue(uNum,uPass,IPName);
                }

                break;
            case R.id.configIP:
                dialog.setMessage("正在检查配置");
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                View view = LayoutInflater.from(this).inflate(R.layout.input_network_dialog, (ViewGroup) getWindow().getDecorView(),false);
                builder.setView(view);
                final EditText companyName = (EditText) view.findViewById(R.id.companyName);
                final EditText IpPass = (EditText) view.findViewById(R.id.ipPass);
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        String name = companyName.getText().toString().trim();
                        String ipass = IpPass.getText().toString().trim();
                        presenter.ipCheck(name,ipass);
                    }
                });
                builder.show();
                break;
        }
    }


    @Override
    public void showProgress() {
        if (dialog!=null){
            dialog.show();
        }
    }

    @Override
    public void hideProgress() {
        if (dialog.isShowing()){
            dialog.dismiss();
        }
    }
    @Override
    public void shakeUserName() {
        if(userNum.getAnimation()!=null){
            userNum.clearAnimation();
        }
        userNum.setAnimation(shake);
        userNum.startAnimation(shake);
    }

    @Override
    public void shakeUserPass() {
        if(userPass.getAnimation()!=null){
            userPass.clearAnimation();
        }
        userPass.setAnimation(shake);
        userPass.startAnimation(shake);
    }

    @Override
    public void shakeIPCheck() {
        if (configIP.getAnimation() != null) {
            configIP.clearAnimation();
        }
        configIP.setAnimation(shake);
        configIP.startAnimation(shake);
    }

    @Override
    public void clearShopAndScheduleData() {
        try {
            clearShopAndSchedule();
        } catch (DbException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void saveEmp() {
        saveUserInfo();
    }

    @Override
    public void setUserNameErro() {
        BaseActivity.showAnimaDialog(this,"用户名不存在");
    }

    @Override
    public void setUserPassErro() {
        BaseActivity.showAnimaDialog(this,"密码错误");
    }

    @Override
    public void toMainActivity() {
        Employee emp= null;
        try {
            emp = db.selector(Employee.class).where("usernum","=",uNum+"").findFirst();
            int userId=emp.getID();
            String firstName=emp.getFirstName();
            Intent in=new Intent(this, SynchronizationAtivity.class);
            in.putExtra("userId",userId);
            in.putExtra("userName",firstName);
            startActivity(in);
            presenter.onDestory();
            finish();
        } catch (DbException e) {
            e.printStackTrace();
        }

    }

    @Override
    public void inputAllInfo() {
        showAnimaDialog(this,"请输入完整信息");
    }

    @Override
    public void ipConfigOk(){
       showAnimaDialog(this,"配置检验成功，请登录");
    }

    @Override
    public void ipCnonfigFailed() {
        showAnimaDialog(this,"该地址未配置入服务器，请联系管理员");
    }

    //回调用户信息
    @Override
    public void returnEmpList(List<Employee> emps) {
        try {
            db.saveOrUpdate(emps);
        } catch (DbException e) {
            e.printStackTrace();
        }
    }



    //回调ip请求数据
    @Override
    public void returnIpConfig(String code, String branchName) {
        SharedPreferences.Editor ed=sp.edit();
        ed.putString("IpName",code);
        ed.putString("branchName",branchName);
        ed.apply();
        pubClass.seturl(this);
    }

    //IP保存在sharepreference中
    public void saveUserInfo(){
        SharedPreferences.Editor ed=sp.edit();
        ed.putString("userNum",uNum);
        ed.putString("userPass",uPass);
        ed.apply();
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        //光标在text后面
        userNum.setSelection(userNum.length());
        if(userNum.length()==0&&userPass.length()>0){
            userPass.setText("");
        }
    }

    //登录清除门店，日程数据,防止日程或门店删除本地有数据
    public void clearShopAndSchedule() throws DbException {
        final List<Schedule> sch = db.selector(Schedule.class).findAll();
        if (sch!=null&&sch.size()>0){
            db.delete(Schedule.class);
        }
        final List<Shop> shops = db.selector(Shop.class).findAll();
        if (shops!=null&&shops.size()>0){
            db.delete(Shop.class);
        }
    }
}

